<?php


namespace api\zhengmaotong\controller;

use api\zhengmaotong\model\AddressModel;
use api\zhengmaotong\validate\AddressValidate;
use cmf\controller\RestBaseController;
use think\Request;

class AddressController extends RestBaseController
{
    //获取收获地址列表
    public function getAddressList(){

        $list = AddressModel::order('id','desc')
            ->field('id,name,mobile,area,xxdz')
            ->select();
        $this->success('地址收货信息列表',$list);
    }
    //添加收货
    public function addAddress(Request $request){
        $data = input('post.');
        //验证数据
        $data['user_id']= $request->userId;
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            return error($validate->getError());
        }
        $add = AddressModel::create($data);
        if($add){
            return success('添加成功',[
                'data'=>$data
            ]);
        }
        return error('添加失败');
    }
    //修改收货地址
    public function editAddress(){
        $id = input('id');
        $data = input();
        //验证
        $validate = new addressValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            return error($validate->getError());
        }
       // $edit = addressModel :where('id',$data['id'])->update($data);
        $user = AddressModel::where('id',$id)->find();
        $user->mobile = $data['mobile'];
        $user->name = $data['name'];
        $user->area = $data['area'];
        $user->xxdz = $data['xxdz'];
        if($user->save()){
            return success('保存成功',[
                'data'=>$data
            ]);
        }
        return error('保存失败');
    }
        //删除收货地址
    public function delAddress($id)
    {
        $address = AddressModel::find($id);
        if (!$address) {
            $this->error('地址不存在');
        }

        if ($address->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('这是删除失败');
        }
    }
}